package com.letv.so.servlet;

import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.letv.so.bean.AlbumBean;
import com.letv.so.bean.ExtranetAlbumBean;
import com.letv.so.bean.VideoBean;
import com.letv.so.constants.Constants;
import com.letv.so.util.BisUtil;
import com.letv.so.util.SoKeyUtil;
import com.letv.so.util.SpecialFieldUtil;
import com.letv.so.util.StringUtil;
import com.letv.so.util.ThreadLocalUtil;

/**
 * cbase相关站点接口
 * 
 * @author wenjian
 * 
 */
public class QueryCbaseWebSiteServlet extends AbstractQueryDataServlet {

	private static final long serialVersionUID = -2626713538347997214L;
	private static final Logger logger = LoggerFactory.getLogger(QueryCbaseWebSiteServlet.class);

	/**
	 * 查询相关站点信息
	 */
	protected String query(Map<String, Object> rule) {
		String reData = null;
		try {
			long starttime = System.currentTimeMillis();
			List<ExtranetAlbumBean> eAlbumList = new ArrayList<ExtranetAlbumBean>();
			String sid = (String) rule.get("sid");
			String soKey = (String) rule.get("soKey");// 获得request sokey
			String src = SoKeyUtil.getSrc(soKey);// 获得前缀vrs_,leso_
			String targetWebSit = SoKeyUtil.getWebSite(soKey);
			String lesoAid = getLesoAid(soKey, src);// 解析sokey获得leso专辑ID
			String pcp = (String) rule.get("pcp");
			boolean ifCibn = false;    // true-- 请求方需要pushflag=420007&cibn过审的数据
			if(!StringUtils.isBlank(pcp) && Constants.PCP_FOR_CIBN.equals(pcp)) {
			    ifCibn = true;
			}
			String website_id_list = (String) rule.get("website_id_list");
			boolean ifTarget = !StringUtils.isBlank(website_id_list); // 请求方指定所需站点源列表
			int pn = (Integer) rule.get("pn");//
			int ps = (Integer) rule.get("ps");// 每页多少个
			logger.info(sid+","+soKey + ",QueryCbaseWebSiteServlet.query targetWebSit:" + targetWebSit + ",lesoAid:" + lesoAid);
			if (StringUtils.isNotBlank(soKey) && StringUtils.isNotBlank(targetWebSit)) {
				return getPageVideoWebSite(starttime, sid, soKey, lesoAid, targetWebSit, pn, ps, ifCibn, ifTarget, website_id_list);// 转为json格式
			}
			long cbasetime =0;
			if (lesoAid == null) {
				eAlbumList.add(this.getExAlbumBySokey(sid, soKey));
			} else {
				List<String> soKeyList = CommonServlet.getWebsiteSokeyList(lesoAid, website_id_list);
				long a1 = System.currentTimeMillis();
				List<String> soDataList = queryDataService.getMulti(sid,soKeyList);
				cbasetime = System.currentTimeMillis() - a1;
				List<String> onlyNotPay = SpecialFieldUtil.getConfigList(rtnkeys, ThreadLocalUtil.getFrom(),SpecialFieldUtil.WEBSITE_NOT_CONTIANT);
				for (String soData : soDataList) {
					if (!StringUtil.isBlank(soData)) {
						ExtranetAlbumBean eAlbum = JSON.parseObject(soData, ExtranetAlbumBean.class);
						if (eAlbum != null) {
                            if(!CommonServlet.websiteIfOn(ifTarget, eAlbum, ifCibn)) {
                                continue;
                            }
						    if(ifCibn) {
						        if(!StringUtils.isBlank(eAlbum.getTop_hot_tv())) {
						            eAlbum.setTophot(eAlbum.getTop_hot_tv());
						            eAlbum.setOrderNum(eAlbum.getTop_hot_tv());
						        }
						    } else {
						        if(!StringUtils.isBlank(eAlbum.getTop_hot_def())) {
						            eAlbum.setTophot(eAlbum.getTop_hot_def());
						            eAlbum.setOrderNum(eAlbum.getTop_hot_def());
						        }
						    }
							String site = eAlbum.getSite();
		                    if (Constants.WEBSITE_LETV.equals(site)) {
		                    	eAlbum.setLetv_original_id(Constants.VRS_ALBUM_PERFIX+eAlbum.getVrsAid());
		                    } else {
		                    	eAlbum.setLetv_original_id(Constants.LESO_ALBUM_PERFIX+eAlbum.getAid());
		                    }
						    if ( onlyNotPay !=null ) {
						        if ( SpecialFieldUtil.matchConfig(onlyNotPay,eAlbum,SpecialFieldUtil.FILEDS_SEP_EQU)) {
						            String videoSingleVideoImages = getSigleVideoImageStr(eAlbum);
						            setWebsiteVl(eAlbum,videoSingleVideoImages,sid,soKey,ps,pn);
						            eAlbumList.add(eAlbum);
						        }
		                        continue;
						    }
							if ( site != null && ! site.equals(targetWebSit)) {// 非指定站点不需要剧集列表
								eAlbum.setVideoList(null);
							} else {
								List<VideoBean> list = eAlbum.getVideoList();
								String eaid = "";
								if (Constants.SRC_LESO.equals(src)) {
									eaid = eAlbum.getAid();
								} else {
									eaid = eAlbum.getVrsAid();
								}
								Map<String,String> globalVids = new HashMap<String,String>();
								convertStr2Map(eAlbum.getUnIds(),globalVids);
								if (null != list && list.size() > 0) {
									for (VideoBean videoBean : list) {
										// 每个视频添加唯一全局id
										String aorder = "1";
										if (StringUtils.isNotBlank(videoBean.getAorder())) {
											aorder = videoBean.getAorder();
										}
										videoBean.setGlobal_vid(eaid + "_" + aorder + "_" + MD5(videoBean.getUrl()));
										videoBean.setUnid(globalVids.get(aorder));
										setPayAndDownFlag(videoBean);
									}
								}
	                           int rmN =  removeOneVideo(eaid,list);
	                           changeOrderLstAndEps(rmN,eAlbum);
							}
				            if (TRADITIONAL.contains(ThreadLocalUtil.getLang())){
				                eAlbum.sample2traditional(converter);
				            }
				            eAlbum.setNull();
							eAlbumList.add(eAlbum);
						}
					}
				}
			}
			CommonServlet.websiteSort(ifTarget, eAlbumList);
			reData = JSON.toJSONString(eAlbumList, SerializerFeature.WriteTabAsSpecial);
			logger.info(sid+",QueryCbaseWebSiteServlet, total time=["+(System.currentTimeMillis()-starttime)+"],cbase time=["+cbasetime+"]");
			if (StringUtil.isBlank(reData)) {
				return "{}";
			}

		} catch (Exception e) {
			logger.error("QueryCbaseServlet.query error", e);
			return "{}";
		}
		return reData;
	}

	private void changeOrderLstAndEps(Integer rmN, ExtranetAlbumBean eAlbum) {
        if (rmN > 0 ) {
           String np =  eAlbum.getNowEpisodes();
           if (rmN.toString().equals(np)) {
               eAlbum.setNowEpisodes(""+(rmN-1));
           }
           String orderlst = eAlbum.getOrderlist();
           String removeStr = getRemoveStr(rmN);
           if (StringUtils.isNotEmpty(orderlst) && orderlst.contains(removeStr)) {
               eAlbum.setOrderlist(orderlst.replace(removeStr, ";"));
           }
        }
    }

    private String MD5(String s) {
		char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D',
		        'E', 'F' };
		try {
			byte[] btInput = s.getBytes();
			// 获得MD5摘要算法的 MessageDigest 对象
			MessageDigest mdInst = MessageDigest.getInstance("MD5");
			// 使用指定的字节更新摘要
			mdInst.update(btInput);
			// 获得密文
			byte[] md = mdInst.digest();
			// 把密文转换成十六进制的字符串形式
			int j = md.length;
			char str[] = new char[j * 2];
			int k = 0;
			for (int i = 0; i < j; i++) {
				byte byte0 = md[i];
				str[k++] = hexDigits[byte0 >>> 4 & 0xf];
				str[k++] = hexDigits[byte0 & 0xf];
			}
			return new String(str);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	private String getOrderList(String vidList) {
		StringBuffer sb = new StringBuffer();
		if (StringUtils.isNotBlank(vidList)) {
			String[] vidArray = vidList.split(";");
	        for (int i = 0; i < vidArray.length; i++) {
	        	if (StringUtils.isBlank(vidArray[i])) {
	                continue;
                }
	        	String[] videoFileds = vidArray[i].split("\\|");
				if (videoFileds.length==1) {//过滤不规范的数据
                    continue;
                }
	            sb.append(videoFileds[0]);
	        	if (i!=vidArray.length) {
	                sb.append(";");
                }
            }
        }
		
		return sb.toString();
	}
	
	private String getTaglist(String vidLists, int ps,String string) {
		StringBuffer tags = new StringBuffer();
		int count = 0;
		int totalnum = 0;
		if (StringUtils.isNotBlank(vidLists)) {
			
			count = vidLists.split(";").length / ps;
			if (vidLists.split(";").length % ps != 0) {
				count ++;
            }
			totalnum = vidLists.split(";").length;
			tags.append("all:1-").append(count).append(":");
		}
		boolean beginZero = (StringUtil.isNotEmpty(string)&& string.split("\\|")[0].equals("0"));
		int index = beginZero?(totalnum-1):totalnum;
		int one = beginZero?1:0;
		int zero = beginZero?0:1;
		for (int i = 0; i < count; i++) {
			int start = zero + i * ps;
			int end =  ((i + 1) * ps)-one;
			if (index>=end) {
				tags.append(start).append("-").append(end);
            } else {
            	if (index==start) {
            		tags.append(start);
                } else {
                	tags.append(start).append("-").append(index);
                }
            }
	        if (i!=count) {
	        	tags.append(";");
            }
        }
		
//		for (int i = 0; i < count; i++) {
//			int start = 1 + i * ps;
//			int end =  (i + 1) * ps;
//	        tags.append(start).append("-").append(end);
//	        if (i!=count) {
//	        	tags.append(";");
//            }
//        }
		
		return tags.toString();
	}

	/**
	 * 解析sokey获得leso专辑ID
	 * 
	 * @param soKey
	 * @return
	 */
	private String getLesoAid(String soKey, String src) {
		String lesoAid = "";
		if (Constants.SRC_VRS.equals(src)) { // sokey如果对应的是vrs的专辑需要一次查询，才能获得lesoAid
			soKey = "newleso_la_" + SoKeyUtil.getID(soKey);
			String soData = queryDataService.get(soKey);
			if (StringUtil.isBlank(soData)) {
				return null;
			}
			ExtranetAlbumBean eAlbum = JSON.parseObject(soData, ExtranetAlbumBean.class);
			lesoAid = eAlbum.getAid();

		} else if (Constants.SRC_LESO.equals(src)) { // sokey如果对应的是leso专辑，直接解析，即可获得lesoAid
			lesoAid = SoKeyUtil.getID(soKey);
		}
		return lesoAid;
	}

	/**
	 * 乐视独家封装站点信息
	 * 
	 * @param soKey
	 * @return
	 */
	private ExtranetAlbumBean getExtranetAlbumBeanWithVrsAid(String sid, String soKey) {
		ExtranetAlbumBean eAlbum = new ExtranetAlbumBean();
		soKey = SoKeyUtil.getSoKey(Constants.SRC_VRS, Constants.ALBUM, SoKeyUtil.getID(soKey), true);

		String soData = queryDataService.get(sid,"inc" + soKey);
		if (StringUtils.isBlank(soData)) {
			soData = queryDataService.get(sid,soKey);
		}

		if (StringUtils.isNotBlank(soData)) {
			AlbumBean a = JSONObject.parseObject(soData, AlbumBean.class);
			eAlbum.setVrsAid(a.getAid());
			eAlbum.setSite(Constants.WEBSITE_LETV);
			eAlbum.setDataType(Constants.ALBUM);
			eAlbum.setIsTv("1");
			eAlbum.setIsMobile("1");
			eAlbum.setIsPc("1");
		}

		return eAlbum;
	}

	/**
	 * 外网剧集列表封装
	 * 
	 * @param lesoAid
	 * @param website
	 * @param pn
	 * @param ps
	 * @param ifCibn 
	 * @param ifTarget 
	 * @param website_id_list 
	 * @return
	 */
	private String getPageVideoWebSite(long st, String sid, String key, String lesoAid, String website, int pn, int ps, boolean ifCibn, boolean ifTarget, String website_id_list) {
		List<ExtranetAlbumBean> eAlbumList = new ArrayList<ExtranetAlbumBean>();
		List<AlbumBean> eAlbumList1 = new ArrayList<AlbumBean>();
		String soData = "";
		try {
			long cbasetime = 0;
			long a1 = System.currentTimeMillis();
			if (StringUtils.isBlank(lesoAid)) {
				String soKey = SoKeyUtil.getSoKey(Constants.SRC_VRS, Constants.ALBUM, SoKeyUtil.getID(key), true);
				String soData1 = queryDataService.get(sid,"inc"+soKey);// 获得cbase数据
				logger.info("start get from cbase,sid="+sid+",sokey="+soKey );
				if (StringUtils.isBlank(soData1)) {
					soData1 = queryDataService.get(sid,soKey);// 获得cbase数据
	            }
				AlbumBean album =null;
				try {
					album = JSON.parseObject(soData1, AlbumBean.class);
				} catch (Exception e) {
					logger.error(sid+" ,parse album error", e);
				}
				if (album == null) {
					logger.warn(sid+ " ,soKey:"+soKey+" album==null ");
					logger.info("soData is blank,start get Extranet Album,sid="+sid+",sokey="+key );
					eAlbumList.add(getExAlbumBySokey(sid,key));	
					cbasetime = System.currentTimeMillis() -a1;
					soData = JSON.toJSONString(eAlbumList, SerializerFeature.WriteTabAsSpecial);// 转为json格式
					logger.info("soData is blank,return Extranet Album,sid="+sid+",sokey="+key );
				} else {
				if (soKey.contains("newmms")) {// request要求有剧集列表，则封装
					try{setVideoList(sid, soKey, album,ps,pn,ps,true);}catch(Exception e){logger.error("setVideoList Error",e);}					
				}
			    
				logger.info("lesoAid="+lesoAid+",start parse album,sid="+sid+",sokey="+soKey );
				album.setSite("letv");
				//屏蔽外网不显示的字段
				album.setGlobalVids(null);
				album.setShortDesc(null);
				album.setVideoPlayUrls(null);
				album.setStarsPoster(null);
				album.setDirectoriesPoster(null);
				album.setActor(null);
				album.setActorName(null);
				album.setActorPlay(null);
				album.setAuthors(null);
				album.setCompose(null);
				album.setContentRating(null);
				album.setCopyright(null);
				album.setCountry(null);
				album.setDayCount(null);
				album.setMonthCount(null);
				album.setDirectory(null);
				album.setDeadlinks(null);
				album.setWeekCount(null);
				album.setTag(null);
				album.setDetailUrl(null);
				album.setDuration(null);
				album.setEnglishName(null);
				album.setIntro(null);
				album.setLanguage(null);
				album.setNameJianpin(null);
				album.setNameQuanpin(null);
				album.setPushFlag(null);
				album.setUrl(null);
				album.setViewPics(null);
				//屏蔽内网不显示的字段
				album.setFitAge(null);
				album.setIsdelete(null);
				album.setCtime(null);
				album.setMtime(null);
				album.setPayPlatform(null);
				album.setPayProduct(null);
				album.setPublishCompany(null);
				album.setRcompany(null);
				album.setRecordCompany(null);
				album.setTvid(null);
				album.setTvTitle(null);
				album.setWebsiteTitle(null);
				album.setVarietyShow(null);
				album.setDoubanid(null);
				album.setQname(null);
				album.setLetvReleaseDate(null);
				album.setOtherName(null);
				album.setDownloadPlatform(null);
				album.setDuration(null);
				album.setEnglishName(null);
				album.setHasHeight(null);
				album.setIsHomemade(null);
				album.setMaker(null);
				album.setSourceid(null);
				album.setSubname(null);
				album.setVidEpisode(null);
				album.setVideoType(null);
				album.setVideoTypeName(null);
				album.setVids(null);
				album.setStyle(null);
				album.setName_pinyin_abb(null);
				album.setPicOriginal(null);
				album.setPicOriginal(null);
//				album.setPlayStreams(null);
				album.setPushFlag(null);
				album.setRelationid(null);
				album.setScreenwriter(null);
				album.setMobileTitle(null);
				album.setPlayCount(null);
				album.setPlayStatus(null);
				album.setStatus(null);
				album.setArea(null);
				album.setAreaName(null);
				album.setCategoryName(null);
				album.setDirectoryName(null);
				album.setImages(null);
				album.setIsEnd(null);
				album.setIspay(null);
				album.setName(null);
				album.setPanid(null);
				album.setRating(null);
				album.setReleaseDate(null);
				album.setStarring(null);
				album.setStarringName(null);
				album.setStarringPlay(null);
				album.setSubCategory(null);
				album.setSubCategoryName(null);
				album.setIntro(album.getDescription());
				album.setDescription(null);
				album.setIsMobile("1");
				album.setIsTv("1");
				album.setIsPc("1");
				album.setOrderNum("0");
				album.setTophot("0");
				album.setVrsAlbumId(album.getAid());
				album.setLetv_original_id(Constants.VRS_ALBUM_PERFIX+album.getAid());
				List<VideoBean> listVideo = album.getVideoList();
				//album.setUnIds(null);
				if (listVideo!=null){
				List<VideoBean> tmpList = new ArrayList<VideoBean>();
				int isbeginZero = (StringUtil.isNotEmpty(album.getOrderlist())&&album.getOrderlist().split(";")[0].equals("0"))?0:1;
				for (VideoBean videoBean : listVideo) {
					VideoBean vb = new VideoBean();
					vb.setAorder((isbeginZero++)+"");
					vb.setDataType(videoBean.getDataType());
					vb.setDeadlink(videoBean.getDeadlink());
					vb.setGlobal_vid(videoBean.getGlobal_vid());
					vb.setMid(videoBean.getMid());
					vb.setName(videoBean.getName());
					vb.setPlayStreams(videoBean.getPlayStreams());
					vb.setSubName(videoBean.getSubName());
					vb.setUrl(videoBean.getUrl());
					vb.setPayPlatform(videoBean.getPayPlatform());
					vb.setDownloadPlatform(videoBean.getDownloadPlatform());
					vb.setIsPay(videoBean.getIsPay());
					vb.setVid(videoBean.getVid());
					vb.setVideoPanid(videoBean.getVideoPanid());
					vb.setUnid(videoBean.getUnid());
		            if (TRADITIONAL.contains(ThreadLocalUtil.getLang())){
		                vb.sample2traditional(converter);
		            }
                    setPayAndDownFlag(vb); 
					tmpList.add(vb);
				}
				album.setVideoList(tmpList);
				}
			  eAlbumList1.add(album);
              if (TRADITIONAL.contains(ThreadLocalUtil.getLang())){
                  album.sample2traditional(converter);
              }
			  soData = JSON.toJSONString(eAlbumList1, SerializerFeature.WriteTabAsSpecial);// 转为json格式
			  cbasetime = System.currentTimeMillis() -a1;
				}
			} else {
			    setWebsiteAlbumList(eAlbumList,website,lesoAid,sid,key,pn,ps, ifCibn, ifTarget, website_id_list);
			    CommonServlet.websiteSort(ifTarget, eAlbumList);
				cbasetime = System.currentTimeMillis() -a1;
				soData = JSON.toJSONString(eAlbumList, SerializerFeature.WriteTabAsSpecial);// 转为json格式
			}
			logger.info(sid+",QueryCbaseWebSiteServlet, total time=["+(System.currentTimeMillis()-st)+"],cbase time=["+cbasetime+"]");
			if (StringUtils.isBlank(soData)) {
				soData = "{}";
			}
			return soData;
		} catch (Exception e) {
			logger.error("QueryCbaseServlet.query error", e);
			return "{}";
		}

	}

	private ExtranetAlbumBean getExAlbumBySokey(String sid, String key) {
		ExtranetAlbumBean ea = getExtranetAlbumBeanWithVrsAid(sid,key);
		String vrsaid = ea.getVrsAid();
		ea.setLetv_original_id(Constants.VRS_ALBUM_PERFIX+vrsaid);
		List<VideoBean> list = ea.getVideoList();
		if (null != list && list.size() > 0) {
			for (VideoBean videoBean : list) {
				// 每个视频添加唯一全局id,lesoAid为null
				String aorder = "1";
				if (StringUtils.isNotBlank(videoBean.getAorder())) {
					aorder = videoBean.getAorder();
				}
				videoBean.setGlobal_vid(vrsaid + "_" + aorder + "_" + MD5(videoBean.getUrl()));
			}
		}
		return ea;
	}

	private void setWebsiteAlbumList(List<ExtranetAlbumBean> eAlbumList,
            String website, String lesoAid, String sid, String key, int pn, int ps, boolean ifCibn, boolean ifTarget, String website_id_list) {
	    List<String> soKeyList = CommonServlet.getWebsiteSokeyList(lesoAid, website_id_list);
        List<String> soDataList = queryDataService.getMulti(sid,soKeyList);
        for (String soData1 : soDataList) {
            if (StringUtil.isNotBlank(soData1)) {
                ExtranetAlbumBean eAlbum = JSON.parseObject(soData1, ExtranetAlbumBean.class);
                if (eAlbum != null) {
                    if(!CommonServlet.websiteIfOn(ifTarget, eAlbum, ifCibn)) {
                        continue;
                    }
                    if(ifCibn) {
                        if(!StringUtils.isBlank(eAlbum.getTop_hot_tv())) {
                            eAlbum.setTophot(eAlbum.getTop_hot_tv());
                            eAlbum.setOrderNum(eAlbum.getTop_hot_tv());
                        }
                    } else {
                        if(!StringUtils.isBlank(eAlbum.getTop_hot_def())) {
                            eAlbum.setTophot(eAlbum.getTop_hot_def());
                            eAlbum.setOrderNum(eAlbum.getTop_hot_def());
                        }
                    }
                    eAlbum.setSrc("2");//站点源为固定值
                    String videoSingleVideoImages = getSigleVideoImageStr(eAlbum);
                    String site = eAlbum.getSite();
                    if (site != null && ! site.equals(website)) {// 非指定站点不需要剧集列表
                        eAlbum.setVideoList(null);
                    } else {
                        setWebsiteVl(eAlbum,videoSingleVideoImages,sid,key,ps,pn);
                    }
                    if (Constants.WEBSITE_LETV.equals(site)) {
                    	eAlbum.setLetv_original_id(Constants.VRS_ALBUM_PERFIX+eAlbum.getVrsAid());
                    } else {
                    	eAlbum.setLetv_original_id(Constants.LESO_ALBUM_PERFIX+eAlbum.getAid());
                    }
                    if (TRADITIONAL.contains(ThreadLocalUtil.getLang())){
                        eAlbum.sample2traditional(converter);
                    }
                    eAlbumList.add(eAlbum);
                }
            }
        }
    }

    private String getSigleVideoImageStr(ExtranetAlbumBean eAlbum) {
        String rtnStr = null;
        if(SpecialFieldUtil.checkSingleField(this.rtnkeys,ThreadLocalUtil.getFrom(), "website", "videoList.images", true)) {
            rtnStr = eAlbum.getVideoSingleVideoImages();
        }
        if(!SpecialFieldUtil.checkSingleField(this.rtnkeys,ThreadLocalUtil.getFrom(), "website", "videoSingleVideoImages", true)) {
            eAlbum.setVideoSingleVideoImages(null);
        }
        return rtnStr;
    }

    private void setWebsiteVl(ExtranetAlbumBean eAlbum,
            String videoSingleVideoImages, String sid, String key, int ps, int pn) {
//      String videoPlayUrls = eAlbum.getVideoPlayUrls();
        // 死链map
        Map<String, String> deadlinkMap = new HashMap<String, String>();
        String deadlinks = eAlbum.getVideoDeadlinkUrls();
        convertStr2Map(deadlinks,deadlinkMap);
        // 单视频流截图map
        Map<String, String> singlevideoImageMap = new HashMap<String, String>();
        String singlevideoImages = videoSingleVideoImages;
        convertStr2Map(singlevideoImages,singlevideoImageMap);
        List<VideoBean> list = eAlbum.getVideoList();
        if (null!=list && list.size()!=0) {
            String[] infoArray = StringUtil.isNotBlank(eAlbum.getIntro()) ? eAlbum.getIntro().split(";") : new String[0];
            List<String> infoLists = Arrays.asList(infoArray);
            // pn默认为0，ps默认为50
            int size = list.size();
            int fromIndex = pn * ps;
            int toIndex = (pn + 1) * ps;
            List<String> externalIds = BisUtil.subList(fromIndex, toIndex, BisUtil.getList(eAlbum.getExternal_ids()));
            List<String> videoTypes = BisUtil.subList(fromIndex, toIndex, BisUtil.getList(eAlbum.getVideoTypes()));
            List<String> externalPlayIds = BisUtil.subList(fromIndex, toIndex, BisUtil.getList(eAlbum.getExternal_play_ids()));
            List<VideoBean> retVids = new ArrayList<VideoBean>();
            List<String> retInfos = new ArrayList<String>();
            if (toIndex <= size) {
                retVids = list.subList(fromIndex, toIndex);
            } else {
                if (fromIndex < size) {
                    retVids = list.subList(fromIndex, size);
                }
            }
            int size1 = infoLists.size();
            if (toIndex <= size1) {
                retInfos = infoLists.subList(fromIndex, toIndex);
            } else {
                if (fromIndex < size1) {
                    retInfos = infoLists.subList(fromIndex, size1);
                }
            }
            String aid = eAlbum.getAid();
            String subSrc = eAlbum.getSite();
            Map<String,String> globalVids = new HashMap<String,String>();
            convertStr2Map(eAlbum.getUnIds(),globalVids);
            for (int i = 0; i < retVids.size(); i++) {
                VideoBean video = retVids.get(i);
                String videoUrl = video.getUrl();
                if (!StringUtil.isBlank(videoUrl)  && (!StringUtil.isBlank(subSrc)) && ("nets".equals(subSrc) || "pan".endsWith(subSrc))) {
                    int len = videoUrl.lastIndexOf('/') + 1;
                    video.setVideoPanid(videoUrl.substring(len));
                } else {
                    video.setVideoPanid("");
                }
                String[] videoInfo = retInfos.size() > i ? retInfos.get(i).split("\\|") : new String[0];
                video.setName(videoInfo.length > 1 ? videoInfo[1] : "");
                video.setSubName(videoInfo.length > 1 ? videoInfo[1] : "");

                // 每个视频添加唯一全局id
                String porder = "1";
                if (StringUtils.isNotBlank(video.getAorder())) {
                    porder = video.getAorder();
                }
                video.setGlobal_vid(aid + "_" + porder + "_" + MD5(video.getUrl()));
                String gvid = globalVids.get(video.getAorder());
                video.setUnid(gvid);
                // 添加死链
                if (deadlinkMap.size() > 0 && deadlinkMap.containsKey(video.getAorder())) {
                    video.setDeadlink(deadlinkMap.get(video.getAorder()));
                } else {
                    video.setDeadlink("0");
                }
                String[] externelid = externalIds.size() > i ? externalIds.get(i).split("\\|") : new String[0];
                video.setExternal_id(externelid.length > 1 ? externelid[1] : "");
                String[] videoType = videoTypes.size() > i ? videoTypes.get(i).split("\\|") : new String[0];
                video.setVideoType(videoType.length > 1 ? videoType[1] : "");
                String[] externalPlayId = externalPlayIds.size() > i ? externalPlayIds.get(i).split("\\|") : new String[0];
                String externalPlayIdJsonString = externalPlayId.length > 1 ? externalPlayId[1] : "";
                if(StringUtils.isBlank(externalPlayIdJsonString)) {
                    video.setExternal_play_id(new JSONObject());
                } else {
                    try {
                        video.setExternal_play_id(JSON.parseObject(externalPlayIdJsonString));
                    } catch(Exception externalPlayIdError) {
                        video.setExternal_play_id(new JSONObject());
                    }
                }
                // 添加单视频流截图
                if (singlevideoImageMap.size() > 0 && singlevideoImageMap.containsKey(video.getAorder())) {
                    video.setImages(singlevideoImageMap.get(video.getAorder()));
                } else {
                    logger.debug(key + ", videoPlayUrls 与 images 不匹配");
                }
                if (TRADITIONAL.contains(ThreadLocalUtil.getLang())){
                    video.sample2traditional(converter);
                }
                setPayAndDownFlag(video);
            }
            int rmN = removeOneVideo(aid,retVids);
            if (retVids.size() > 0) {
                eAlbum.setVideoList(retVids);
                eAlbum.setTaglist(getTaglist(eAlbum.getVideoPlayUrls(), ps,eAlbum.getVideoPlayUrls()));
                eAlbum.setOrderlist(getOrderList(eAlbum.getVideoPlayUrls()));
                changeOrderLstAndEps(rmN,eAlbum);
            }
            eAlbum.setNull();
        }
    }

	private String setVideoList(String sid, String soKey1, AlbumBean album, int videoListSize,int pn, int ps,boolean mmsFlag) {
		String time = "";
		long st1 = System.currentTimeMillis();
		String url = album.getUrl();
		String subSrc = album.getSubSrc();
		if (!StringUtil.isBlank(url) && (!StringUtil.isBlank(subSrc)) && ("nets".equals(subSrc) || "pan".endsWith(subSrc))) {
			int len = url.lastIndexOf('/') + 1;
			album.setPanid(url.substring(len));
			album.setSubSrc("nets");
        } else {
        	album.setPanid("");
        }
		String category = album.getCategory();
		List<VideoBean> videoList = new ArrayList<VideoBean>();
		List<String>  tags = new ArrayList<String>();
		List<String> videoTypes = new ArrayList<String>();
		String tagList = "";
		String orderList = "";
		try {
			if (Constants.SRC_VRS.equals(album.getSrc())) {// vrs专辑的剧集列表需要根据album.VidEpisode和.vids二次取cbase
				String aid = album.getAid();
				String idEpisodes = album.getVidEpisode();
				String vids = album.getVids();
				String ralbums = album.getSeriesAlbumIds();
				long s1 = System.currentTimeMillis();
				if(!StringUtils.isBlank(ralbums)){
					setRAlbum(ralbums,album);
				}
				logger.debug(sid+","+soKey1+",SRC_VRS setRAlbum cost time="+(System.currentTimeMillis()-s1));
				List<String> vidLists = new ArrayList<String>();
				List<String> orders = new ArrayList<String>();
				if (!StringUtil.isBlank(vids)) {
					String[] vidArray = vids.split(",");
					String[] idEpisodeArray = null;
					if (StringUtils.isNotBlank(idEpisodes)) {
						idEpisodeArray = idEpisodes.split(",");
                    } else {
                    	idEpisodeArray = new String[]{};
                    }
					// 电影电视剧动漫除外的频道视频列表倒序
					if (String.valueOf(Constants.MMS_MOVIE).equals(category) || String.valueOf(Constants.MMS_TV).equals(category) || String.valueOf(Constants.MMS_CARTOON).equals(category) || String.valueOf(Constants.MMS_OTHER).equals(category)) {
						vidArray = reverse1(vidArray);
					}else {
						idEpisodeArray = reverse1(idEpisodeArray);
					}
					long st2 = System.currentTimeMillis();
					logger.debug(sid+","+soKey1+",SRC_VRS setVideoList, cost time1=" + (st2-st1));
					List<String> allVidLists = Arrays.asList(vidArray);
					List<String> vidEpisodesLists = Arrays.asList(idEpisodeArray);
					logger.debug(sid+","+soKey1+" SRC_VRS vidEpisodesLists="+vidEpisodesLists+",size="+vidEpisodesLists.size());
					
					for (String vidEpisode : vidEpisodesLists) {//先添加正片vid
	                    int len = vidEpisode.indexOf("-");
	                    String vid = vidEpisode.substring(len+1);
	                    vidLists.add(vid);
	                    orders.add(vidEpisode.substring(0, len));//只有正片有order
                    }
					
//					for (String vid : allVidLists) {//添加其他片vid
//	                    if (!vidLists.contains(vid)) {
//	                    	vidLists.add(vid);
//                        }
//                    }
					
					int size = vidLists.size();
					logger.debug(sid+","+soKey1+" SRC_VRS retVids vidLists="+vidLists+",size="+size);
					
					//pn默认为1，ps默认为50
					ps = videoListSize > ps?ps:videoListSize;
					int fromIndex = pn * ps;
					int toIndex = (pn+1) * ps;
					List<String> retVids = new ArrayList<String>();
					if (toIndex<=size) {
						retVids = vidLists.subList(fromIndex, toIndex);
                    }else {
						if (fromIndex<size) {
							retVids = vidLists.subList(fromIndex, size);
                        }
					}
					logger.debug(sid+","+soKey1+",SRC_VRS retVids fromIndex="+fromIndex+",toIndex="+toIndex+",retVids.size="+retVids.size());
					List<String> soDataList = new ArrayList<String>();
					long st3 = System.currentTimeMillis();
					logger.debug(sid+","+soKey1+",SRC_VRS retVids, cost time2=" + (st3-st2));
					for (String vid : retVids) {
						String soKey = SoKeyUtil.getSoKey(album.getSrc(), Constants.VIDEO, vid,mmsFlag);
						String soData = queryDataService.get(sid,"inc"+soKey);
						if (StringUtils.isBlank(soData)) {
							soData = queryDataService.get(sid,soKey);
                        }
						soDataList.add(soData);
                    }
					long st34 = System.currentTimeMillis();
					time = (st34-st3)+",videolist="+retVids.size();
					logger.info(sid+" ,"+soKey1+",SRC_VRS retVids,from cbase total time=[" + (st34-st3)+"],videolist="+retVids.size());
					int i = 1;
					for (String soData : soDataList) {
						if (!StringUtil.isBlank(soData)) {
							VideoBean video = JSON.parseObject(soData, VideoBean.class);
							String videoType = video.getVideoType();
							if ((String.valueOf(Constants.TV).equals(category) || String.valueOf(Constants.CARTOON).equals(category))
									&& Constants.TYPE_ZHENGPIAN.equals(videoType)) {
								video.setUrl("http://www.letv.com/ptv/pplay/" + video.getAid() + "/" + i + ".html");
							} else {
								video.setUrl("http://www.letv.com/ptv/vplay/" + video.getVid() + ".html");
							}
							String videoUrl = video.getUrl();
							if (!StringUtil.isBlank(videoUrl)  && (!StringUtil.isBlank(subSrc)) && ("nets".equals(subSrc) || "pan".endsWith(subSrc))) {
								int len = videoUrl.lastIndexOf('/') + 1;
								video.setVideoPanid(videoUrl.substring(len));
					        } else {
					        	video.setVideoPanid("");
					        }
							if (StringUtils.isNotBlank(video.getPorder())) {
								videoTypes.add(video.getVideoType());
	                        }else {
	                        	videoTypes.add("null");
							}
							if (StringUtils.isNotBlank(video.getPorder())) {
								tags.add(video.getPorder());
	                        }else {
	                        	tags.add("null");
							}
							//每个视频添加唯一全局id
							String porder = "1";
		                	if (StringUtils.isNotBlank(video.getPorder())) {
		                		porder = video.getPorder();
	                        }
		                	video.setGlobal_vid(aid+"_"+porder+"_"+MD5(video.getUrl()));
						    if (video != null) {
							    videoList.add(video);
						    }
							 
						} else {
							tags.add("null");
						}
						i++;
					}
				}
				long st3 = System.currentTimeMillis();
				tagList = getTaglist(vidLists, ps,orders);
				orderList = getOrderlist(orders);
				logger.debug(sid+" ,"+soKey1+",SRC_VRS tagList&orderList cost time4=" + (System.currentTimeMillis()-st3));
			} else if (Constants.SRC_LESO.equals(album.getSrc())) {// leso专辑的剧集列表根据album.videoPlayUrls解析生成
				String videoPlayUrls = album.getVideoPlayUrls();
				 //死链map
				Map<String, String> deadlinkMap = new HashMap<String, String>();
				String deadlinks = album.getDeadlinks();
				if (StringUtils.isNotBlank(deadlinks)) {
					String[] deadlinkArray = deadlinks.split(";");
					if (null!=deadlinkArray) {
						for (String deadlink : deadlinkArray) {
							if (StringUtils.isNotBlank(deadlink)) {
								String[] dd = deadlink.split("\\|");
								if (dd.length==2) {
									deadlinkMap.put(dd[0], dd[1]);
                                }
                            }
                        }
                    }
                }
				long st2 = System.currentTimeMillis();
				logger.debug(sid+" ,"+soKey1+",SRC_LESO deadlinkMap, cost time5=" + (st2-st1));
				if (!StringUtil.isBlank(videoPlayUrls)) {
					List<String> orders = new ArrayList<String>();
					String[] videoArray = videoPlayUrls.split(";");
					for (String vid : videoArray) {
						String[] videoFileds = vid.split("\\|");
						if (videoFileds.length==1) {//过滤不规范的数据
                            continue;
                        }
						orders.add(videoFileds[0]);
                    }
					List<String> vidLists = Arrays.asList(videoArray);
					String[] infoArray = StringUtil.isNotBlank(album.getIntro()) ? album.getIntro().split(";") : new String[0];
					List<String> infoLists = Arrays.asList(infoArray);
					//pn默认为0，ps默认为50
					ps = videoListSize > ps?ps:videoListSize;
					int size = vidLists.size();
					int fromIndex = pn * ps;
					int toIndex = (pn+1) * ps;
					List<String> retVids = new ArrayList<String>();
					List<String> retInfos = new ArrayList<String>();
					if (toIndex<=size) {
						retVids = vidLists.subList(fromIndex, toIndex);
                    }else {
						if (fromIndex<size) {
							retVids = vidLists.subList(fromIndex, size);
                        }
					}
					logger.info(sid+" ,"+soKey1+" SRC_LESO retVids fromIndex="+fromIndex+",toIndex="+toIndex+",videolist="+retVids.size());
					int size1 = infoLists.size();
					if (toIndex<=size1) {
						retInfos = infoLists.subList(fromIndex, toIndex);
                    }else {
                    	if (fromIndex<size1) {
							retInfos = infoLists.subList(fromIndex, size1);
                        }
					}
					
					String aid = album.getAid();
					Map<String,String> globalVids = new HashMap<String,String>();
					convertStr2Map(album.getUnIds(),globalVids);
					long st22 = System.currentTimeMillis();
					logger.debug(sid+" ,"+soKey1+",SRC_LESO videolist, cost time6=" + (st22-st2));
					for (int i=0;i<retVids.size();i++) {
						String vid = retVids.get(i);
						if (StringUtil.isNotBlank(vid)) {
							String[] videoFileds = vid.split("\\|");
							if (videoFileds.length==1) {//过滤不规范的数据
	                            continue;
                            }
							String[] videoInfo = retInfos.size() > i ? retInfos.get(i).split("\\|") : new String[0];
							VideoBean video = new VideoBean();
							video.setDataType(Constants.VIDEO);
							video.setAorder(videoFileds[0]);
							video.setUrl(videoFileds[1]);
							video.setName(videoInfo.length > 1 ? videoInfo[1] : "");
							video.setSubName(videoInfo.length > 1 ? videoInfo[1] : "");
							tags.add(videoFileds[0]);
							String videoUrl = video.getUrl();
							if (!StringUtil.isBlank(videoUrl)  && (!StringUtil.isBlank(subSrc)) && ("nets".equals(subSrc) || "pan".endsWith(subSrc))) {
								int len = videoUrl.lastIndexOf('/') + 1;
								video.setVideoPanid(videoUrl.substring(len));
					        } else {
					        	video.setVideoPanid("");
					        }
							//添加死链
							if (deadlinkMap.size()>0 && deadlinkMap.containsKey(video.getAorder())) {
								video.setDeadlink(deadlinkMap.get(video.getAorder()));
                            } else {
                            	logger.debug(sid+" ,"+soKey1+",SRC_LESO videoPlayUrls 与 deadlinks 不匹配 ");
                            	video.setDeadlink("0");
                            }
							//每个视频添加唯一全局id
							String porder = "1";
		                	if (StringUtils.isNotBlank(video.getAorder())) {
		                		porder = video.getAorder();
	                        }
		                	video.setGlobal_vid(aid+"_"+porder+"_"+MD5(video.getUrl()));
							String gvid = globalVids.get(video.getAorder());
							video.setUnid(gvid);
		                	videoList.add(video);
						} else {
							tags.add("null");
						}
                    }
					album.setVideoPlayUrls(null);
					//album.setUnIds(null);
					logger.debug(sid+","+soKey1+",SRC_LESO videolist, cost time7=" + (System.currentTimeMillis()-st22));
				
					long st3 = System.currentTimeMillis();
					tagList = getTaglist(vidLists, ps,orders);
					orderList = getOrderlist(orders);
					logger.debug(sid+" ,"+soKey1+",SRC_LESO tagList, cost time8=" + (System.currentTimeMillis()-st3));
				}
			}
			if (videoList.size() > 0) {
				album.setVideoList(videoList);
				album.setTaglist(tagList);
				album.setOrderlist(orderList);
			}
		} catch (Exception e) {
			logger.error(sid+",exception: " + e);
		}
		return time;
	}
	
	private String getTaglist(List<String> vidLists, int ps,List<String> orders) {
		StringBuffer tags = new StringBuffer();
		int count = 0;
		if (vidLists.size() != 0) {
			count = vidLists.size() / ps;
			if (vidLists.size() % ps != 0) {
				count ++;
            }
			
			tags.append("all:1-").append(count).append(":");
		}
		boolean beginZero = (orders.size() >0 && orders.get(0).equals("0"));
		int index = beginZero?(vidLists.size()-1):vidLists.size();
		int one = beginZero?1:0;
		int zero = beginZero?0:1;
		for (int i = 0; i < count; i++) {
			int start = zero + i * ps;
			int end =  ((i + 1) * ps)-one;
			if (index>=end) {
				tags.append(start).append("-").append(end);
	        } else {
	            if (index==start) {
	            	tags.append(start);
	            } else {
	                tags.append(start).append("-").append(index);
	            }
	         }
		     if (i!=count) {
		       tags.append(";");
	         }
	    }
		return tags.toString();
	}
	
	private String getOrderlist(List<String> orders) {
		StringBuffer sb = new StringBuffer();
		int size = orders.size();
		for (int i = 0; i < size; i++) {
	        sb.append(orders.get(i));
	        if (i != size) {
	            sb.append(";");
            }
        }
		return sb.toString();
	}
	
	private static String[] reverse1(String[] array) {
		String[] array1 = new String[array.length];
		int j=0;
		if(array.length>0){
			for (int i = array.length-1; i >=0 ; i--) {
				array1[j++]=array[i];
			}		
			return array1;
		}
		return array;
	}
	
	private void setRAlbum(String ids,AlbumBean album){

		List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();

			String[] albums = ids.split(",");
			for(String a:albums){
				if(!StringUtils.isBlank(a)){
					String albumStr = queryDataService.get("mms_vrs_a_"+a);// 获得cbase数据
					logger.debug("albumStr="+albumStr);
					AlbumBean abean =null;
					Map<String,Object> map = new HashMap<String,Object>();
					try {
						abean = JSON.parseObject(albumStr, AlbumBean.class);
					} catch (Exception e) {
						logger.error("parse album error", e);
					}
					if(null !=abean){
						map.put("aid", abean.getAid());
						map.put("name", abean.getName());
						map.put("images", abean.getImages());
					}
					list.add(map);
				}

			}
		
		album.setRelationAlbums(list);
	}
	
	private void convertStr2Map(String strs, Map<String, String> map) {
		if (StringUtils.isNotBlank(strs)) {
			String[] strsArray = strs.split(";");
			if (null!=strsArray) {
				for (String str : strsArray) {
					if (StringUtils.isNotBlank(str)) {
						String[] dd = str.split("\\|");
						if (dd.length==2) {
							map.put(dd[0], dd[1]);
                        }
                    }
                }
            }
        }
	}
}
